package com.hw.common.framework.spring;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class MappingJackson2HttpMessageConverterExt extends MappingJackson2HttpMessageConverter
{
    
    public MappingJackson2HttpMessageConverterExt()
    {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setSerializationInclusion(Include.NON_EMPTY);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(dateFormat);
        this.setObjectMapper(objectMapper);
    }
    
    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException
    {
        
        try
        {
            outputMessage.getHeaders().setContentType(MediaType.parseMediaType("application/json"));
            JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
            JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createGenerator(outputMessage.getBody(), encoding);
                    
            if (this.getObjectMapper().isEnabled(SerializationFeature.INDENT_OUTPUT))
            {
                jsonGenerator.useDefaultPrettyPrinter();
            }
            
            this.getObjectMapper().writeValue(jsonGenerator, object);
        }
        catch (JsonProcessingException ex)
        {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }
}
